package com.szwistar.common.comm.aliyun;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.szwistar.common.comm.SmsService;
import com.szwistar.common.datastruct.JsonMapper;
import com.szwistar.common.datastruct.JsonObject;
import com.szwistar.common.datastruct.Utils;

import org.apache.log4j.PropertyConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * 网易云信短信服务
 */
public class AliyunSmsService implements SmsService {
	protected static final Logger LOG = LoggerFactory.getLogger(AliyunSmsService.class);

	// 访问 URL
	private static final String SysDomain = "dysmsapi.aliyuncs.com";

	// 单实例
	private static AliyunSmsService instance;

	// 获取 APP 服务
	public static SmsService getAppService(String appId) {
		return instance;
	}

	// 客户端连接
	protected IAcsClient client;

	// 应用显示名称
	protected String title;
	// 短信签名(必须是在平台上注册过的)
	protected String signName;
	// 所在区域
	protected String regionId;
	// appKey
	protected String appKey;
	// appSecret
	protected String appSecret;
	// 默认的验证码发送模板
	protected String defaultVerifyTemplateId;

	public String getTitle() { return title; }
	public String getAppKey() { return appKey; }
	public String getAppSecret() { return appSecret; }

	public AliyunSmsService(String title, String signName, String regionId, String appKey, String appSecret, String defaultVerifyTemplateId) {
		super();
		this.title = title;
		this.appKey = appKey;
		this.appSecret = appSecret;
		this.defaultVerifyTemplateId = defaultVerifyTemplateId;
		this.signName = signName;
		this.regionId = regionId;

    	DefaultProfile profile = DefaultProfile.getProfile(regionId, appKey, appSecret);
        client = new DefaultAcsClient(profile);
	}

	@Override
	public boolean send(String[] tels, String templateId, Map<String, Object> smsParam) {
		try {
			// 构建参数
	        CommonRequest request = new CommonRequest();
	        request.setMethod(MethodType.POST);
	        request.setDomain(SysDomain);
	        request.setVersion("2017-05-25");
	        request.setAction("SendSms");
	        request.putQueryParameter("RegionId", regionId);
	        request.putQueryParameter("PhoneNumbers", String.join(",", tels));
	        request.putQueryParameter("SignName", signName);
	        request.putQueryParameter("TemplateCode", templateId);
	        request.putQueryParameter("TemplateParam", JsonMapper.toJson(smsParam));

	        // 发送请求
			CommonResponse response = client.getCommonResponse(request);

	        // 处理返回信息
	        JsonObject ret = JsonMapper.fromJson(response.getData());
			if("OK".equalsIgnoreCase(ret.getStr("Code", null))) { return true; }
			LOG.error("发送短信失败！{}", response.getData());
			return false;
		} catch (Exception e) {
			LOG.error("发送短信失败！", e);
			return false;
		}
	}

	@Override
	public boolean send(String targetTel, String templateId, Map<String, Object> smsParam) {
		String tels[] = { targetTel };
		return send(tels, templateId, smsParam);
	}

	@Override
	public String sendVerify(String targetTel, String templateId) {
		String code = Integer.toString(Utils.random(100000, 999999));
		String tels[] = {targetTel};
		JsonObject params = new JsonObject("code", code);
		return send(tels, templateId, params) ? code : null;
	}

	@Override
	public String sendVerify(String targetTel) {
		return sendVerify(targetTel, defaultVerifyTemplateId);
	}

    public static void main(String[] args) throws Exception {
		PropertyConfigurator.configure("log4j.properties");

        SmsService svc = new AliyunSmsService(null, "智辰科技", "cn-shenzhen", "LTAI4Fy4gFbqz9wU5ZYhMjae", "gbHLgs2mT8Emj4n8GajvLFpLwhzsLO", "SMS_162220494");
        svc.sendVerify("18612345678");
    }
}